using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TankWars
{
    /// <summary>
    /// Abstract class for all movable sprites
    /// </summary>
    public abstract class MovableSprite
    {
        protected Texture2D Sprite;

        public Vector2 vAccel = Vector2.Zero;
        public Vector2 vSpeed = Vector2.Zero;
        public Vector2 vPosition = Vector2.Zero;

        public float fRotation = 0.0f;

        protected Color cSpriteColor = Color.White;

        /// <summary>
        /// Returns the center of the sprite
        /// </summary>
        public Vector2 Origin
        {
            get
            {
                Vector2 origin = new Vector2();
                origin.X = this.Sprite.Width / 2;
                origin.Y = this.Sprite.Height / 2;

                return origin;
            }
        }

        /// <summary>
        /// Updates the position based on the time elapsed and the speed
        /// </summary>
        /// <param name="gameTime"></param>
        public virtual void UpdatePosition(GameTime gameTime)
        {
            //Get previous Speed.
            Vector2 vSpeed0 = this.vSpeed;

            //Update the object's speed.
            this.vSpeed += this.vAccel * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //Calculate the average velocity.
            Vector2 vAvgSpeed = (this.vSpeed + vSpeed0) / 2;

            //Determine the object's new position.
            this.vPosition += vAvgSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
        }

        /// <summary>
        /// Draws the sprite with the SpriteBatch 
        /// </summary>
        /// <param name="spriteBatch"></param>
        public virtual void Draw(SpriteBatch spriteBatch, Map map)
        {
            spriteBatch.Draw(this.Sprite, map.GetTrueScreenPosition(this.vPosition), null, this.cSpriteColor, this.fRotation, this.Origin, 1.0f, SpriteEffects.None, 0.0f);
        }

        /// <summary>
        /// Get a vector perpendicular to the input vector
        /// </summary>
        /// <param name="inputVector">Input vector</param>
        /// <returns></returns>
        public static Vector2 GetPerpendicularVector(Vector2 inputVector)
        {
            float fPerpendicularVectorY = (float)Math.Sqrt(inputVector.Length() / (float)(Math.Pow(Convert.ToDouble(-inputVector.Y / inputVector.X), 2) + 1));
            float fPerpendicularVectorX = (-inputVector.Y * fPerpendicularVectorY) / inputVector.X;

            return new Vector2(fPerpendicularVectorX, fPerpendicularVectorY);
        }
    }
}
